import { createStore } from 'vuex';
import axios from 'axios';
import { ColumnProps, PostProps, UserProps, GlobalErrorProps, ArticleDetail } from './types';
import fetchData from '../hooks/useAxios';
export interface GlobalDataProps {
  token: string;
  error: GlobalErrorProps;
  isLoading: boolean;
  columns: ColumnProps[];
  column?: ColumnProps;
  posts: PostProps[];
  user: UserProps;
  article?: ArticleDetail;
}
const store = createStore<GlobalDataProps>({
  state: {
    token: localStorage.getItem('access_token') || '',
    error: {
      status: false,
      code: 200,
      message: 'Access token'
    },
    isLoading: false,
    columns: [],
    posts: [],
    column: undefined,
    article: undefined,
    user: { isLogin: false, username: 'testUser', column: 1 }
  },
  getters: {
    getColumnsBiggerId(state) {
      return state.columns.filter(column => parseInt(column.id, 10) > 3).length;
    },
    getColumn: state => () => state.column,
    getPosts: state => () => state.posts,
    getOptions: state => () => {
      return state.columns.map(s => {
        return { value: s.code, label: s.title };
      });
    },
    getDetails: state => () => state.article
  },
  actions: {
    async fetchColumns(context) {
      const res = await fetchData('/apixyz/categories/category');
      context.commit('fetchColumns', res.data);
      return res.data;
    },
    async fetchColumn({ commit }, cid) {
      const res = await fetchData(`/apixyz/categories/category/${cid}/info`);
      commit('fetchColumn', res.data);
      return res.data;
    },
    async fetchArticles({ commit }, cid) {
      const res = await fetchData(`/apixyz/articles/bycode/${cid}/articles`);
      commit('fetchArticles', res.data);
      return res;
    },
    async fetchArticleList({ commit }) {
      const res = await fetchData('/apixyz/articles/byuser/lists');
      commit('fetchArticles', res.data);
      return res.data;
    },
    async login({ commit }, payload) {
      const res = await fetchData('/apixyz/users/login', {
        method: 'POST',
        data: payload
      });
      commit('login', res.data);
      return res;
    },
    async fetchCurrentUser({ commit }) {
      const res = await fetchData('/apixyz/users/currentUserInfo');
      commit('fetchCurrentUser', res.data);
      return res;
    },
    async loginAndFetchCurrentUser({ dispatch }, loginData) {
      return dispatch('login', loginData).then(() => {
        return dispatch('fetchCurrentUser');
      });
    },
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    async signup({ commit }, signupData) {
      const res = await fetchData('/apixyz/users/register', {
        method: 'POST',
        data: signupData
      });
      return res;
    },
    // @typescript-eslint/no-unused-vars
    async createPost({ commit }, postData) {
      const res = await fetchData('/apixyz/articles', {
        method: 'POST',
        data: postData
      });
      console.log(res.data);
      return res.data;
    },
    async fetchArticleDetail({ commit }, id) {
      const res = await fetchData(`/apixyz/articles/${id}/detail`);
      commit('setArticleDetail', res.data);
      console.log(res.data, 'res.data');
      return res.data;
    },
    async fetchEditArticle({ commit }, { id, updateObj }) {
      const res = await fetchData(`/apixyz/articles?id=${id}`, {
        method: 'patch',
        data: {
          title: updateObj.title,
          content: updateObj.content,
          cid: updateObj.cid
        }
      });
      commit('setEditArticle', res.data);
      return res;
    },
    async fetchDeleteArticle({ commit }, id) {
      const res = await fetchData(`/apixyz/articles/delete/${id}`, {
        method: 'delete'
      });
      return res.data;
    }
  },
  mutations: {
    login(state, rawData): void {
      // 静态测试数据
      // state.user = { ...state.user, isLogin: true, username: 'shuai' };
      state.token = rawData.data;
      axios.defaults.headers.common.Authorization = 'Bearer ' + state.token;
      localStorage.setItem('access_token', state.token);
    },
    logout(state): void {
      state.token = '';
      localStorage.removeItem('access_token');
      delete axios.defaults.headers.common.Authorization;
    },
    fetchCurrentUser(state, rawData) {
      state.user = { isLogin: true, ...rawData.data };
    },
    createPost(state, newPost): void {
      state.posts.push(newPost);
    },
    setLoading(state, newLoading): void {
      state.isLoading = newLoading;
    },
    fetchColumns(state, rawData) {
      state.columns = rawData.data;
    },
    fetchColumn(state, rawData) {
      state.column = rawData.data;
    },
    fetchArticles(state, rawData) {
      state.posts = rawData.data;
    },
    setArticleDetail(state, newArticleDetail) {
      state.article = newArticleDetail.data;
    },
    setEditArticle(state, newArticleDetail) {
      state.article = newArticleDetail.data;
    },
    setError(state, e: GlobalErrorProps) {
      state.error = e;
    }
  }
});
export default store;
